/**
 * JAVACC DEMO 1.0
 */
package com.dwusoft.ius;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import com.apache.tools.StrUtil;
import com.apache.tools.ToolsMap;

/**
 * description: 系统工具类 
 * @author Hou Dayu 创建时间：2015-12-1  
 * @Copyright(c)2014:东吴软件技术（北京）有限公司
 */
public class IusClassUtil {

	private final String setMethodModify = "set";
	private static IusClassUtil instance;

	private IusClassUtil() {
	}

	public static IusClassUtil getInstance() {
		if (null == instance) {
			instance = new IusClassUtil();
		}
		return instance;
	}

	/**
	 * description:  Map转成JavaBean
	 * @param map
	 * @param obj
	 * @return   
	 */
	@SuppressWarnings("rawtypes")
	public Object convert2Bean(Map<String, Object> map, Object obj, String keyPrefix) {
		Class class1 = obj.getClass();
		Method[] methods = class1.getMethods();
		ToolsMap<Object> utrMap = new ToolsMap<Object>();
		utrMap.putAll(map);
		for (Method method : methods) {
			String methodName = method.getName();
			try {
				if (methodName.startsWith(setMethodModify)) {
					String propertyName = methodName.substring(3);
					Object value = utrMap.get(keyPrefix + propertyName);
					if (!StrUtil.isEmpty(value)) {
						Class<?>[] parameterTypes = method.getParameterTypes();
						String parameterName = parameterTypes[0].getName();
						if (parameterName.indexOf("Integer") != -1) {
							method.invoke(obj, Integer.valueOf(value.toString()));
						} else if (parameterName.indexOf("Long") != -1) {
							method.invoke(obj, Long.valueOf(value.toString()));
						} else {
							method.invoke(obj, String.valueOf(value));
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return obj;
	}

	public Map<String, String> convert2Map(Map<String, Object> map, String keyPrefix) {
		Map<String, String> utrMap = new HashMap<String, String>();
		keyPrefix = keyPrefix + ".";
		for (String key : map.keySet()) {
			try {
				if (key.startsWith(keyPrefix)) {
					String str = key.substring(keyPrefix.length());
					String value = String.valueOf(map.get(key));
					utrMap.put(str, value);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return utrMap;
	}

}
